import {GROUP_BUY_LOAD, GROUP_BUY_LOADING, GROUP_BUY_NOMORE, GROUP_BUY_RESET, GROUP_BUY_HOME_LIST, GROUP_BUY_KEYWORD, GROUP_BUY_RESET_LIST} from '../constants/groupBuy'
import {asyncGoodList, asyncHomeGoodList} from "../api/good";


// 重置社区拼购的状态
export const groupBuyReset = () => {
  return {
    type: GROUP_BUY_RESET
  }
}

// 加载社区拼购首页数据
export const loadHomeList = (homeList) => {
  return {
    type: GROUP_BUY_HOME_LIST,
    homeList
  }
}
export const load = (data) => {
  return {
    type: GROUP_BUY_LOAD,
    data
  }
}

export const setLoading = (bool) => {
  return {
    type: GROUP_BUY_LOADING,
    loading: bool
  }
}

export const nomore = () => {
  return {
    type: GROUP_BUY_NOMORE
  }
}
// 设置关键词
export const setKeyword = (word) => {
  return {
    type: GROUP_BUY_KEYWORD,
    data: word
  }
}

// 对列表进行重置 用于搜索
export const reSetList = () => {
  return {
    type: GROUP_BUY_RESET_LIST
  }
}

// 异步的action 加载首页数据
export function asyncLoadHomeGroupbuy () {
  return (dispatch, getState) => {
    const { token } = getState().user
    const { shop_id } = getState().shop
    if (!token || !shop_id) return // TODO 二者不在的处理

    dispatch(setLoading(true)) // 设置状态 ... 开始加载
    asyncHomeGoodList(token, shop_id, 2).then(({data, status}) => {
      console.log(data)
      if (status) {
        dispatch(loadHomeList(data))
      }
    })
  }
}

// 异步的action 加载分页数据
export function asyncLoadGroupbuy () {
  return (dispatch, getState) => {
    const { page, search } = getState().groupBuy
    const { token } = getState().user
    const { shop_id } = getState().shop
    if (!token || !shop_id) return // TODO 二者不在的处理
    const nextPage = page + 1

    dispatch(setLoading(true)) // 设置状态 ... 开始加载
    asyncGoodList(token, shop_id, 2, page, search).then(({data, status}) => {
      console.log(data)
      if (status) {
        dispatch(load({
          list: data.data,
          page: nextPage,
          nomore: data.data.length < 5,
        }))
        dispatch(setLoading(false)) // 设置状态 ... 加载完毕
      }
    })
  }
}
